<template>
  <div class="users-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser" :disabled="!canUserAdd()">
        <el-icon>
          <Plus />
        </el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header">
          <span>用户列表</span>
          <div class="table-actions">
            <el-button size="small" @click="handleRefresh">
              <el-icon>
                <Refresh />
              </el-icon>
              刷新
            </el-button>
            <el-button size="small" @click="handleExport">
              <el-icon>
                <Download />
              </el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="userList" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar ? row.avatar : ''">
              <template v-if="!row.avatar">{{ row.account.charAt(0) }}</template>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="用户名" width="150" />
        <el-table-column label="部门" width="150">
          <template #default="{ row }">
            {{ getDepartmentName(row.departmentID) }}
          </template>
        </el-table-column>
        <el-table-column prop="isActived" label="状态" width="150">
          <template #default="{ row }">
            <el-tag :type="row.isActived ? 'success' : 'danger'">
              {{ row.isActived ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            {{ Array.isArray(row.roles) ? row.roles.join(', ') : row.role || 'User' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="220" />
        <el-table-column prop="remarks" label="备注" width="260" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" :disabled="!canEditOrDelete()">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="!canEditOrDelete()">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
      :destroy-on-close="true"
    >
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="100px">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="userForm.account" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.id">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="部门" prop="departmentID">
          <el-select v-model="userForm.departmentID" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="dept in departments" :key="dept.id" :label="dept.departName" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认角色" prop="defaultRole">
          <el-select v-model="userForm.defaultRole" placeholder="请选择默认角色" style="width: 100%">
            <el-option label="管理员" value="Admin" />
            <el-option label="普通用户" value="User" />
            <el-option label="访客" value="Guest" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isActived">
          <el-switch v-model="userForm.isActived" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="是否删除" prop="isDeleted">
          <el-switch v-model="userForm.isDeleted" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="userForm.remarks" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Download,
  Edit,
  Delete,
  Switch
} from '@element-plus/icons-vue'
import userAPI from '@/api/user'
import departmentAPI from '@/api/department'
import { useUserStore } from '@/stores/user'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const userFormRef = ref(null)
const selectedUsers = ref([])

// 搜索表单
const searchForm = reactive({
  username: '',
  status: ''
})

// 用户表单
const userForm = reactive({
  id: '',
  account: '',
  password: '',
  departmentID: '',
  defaultRole: 'User',
  isActived: true,
  isDeleted: false,
  remarks: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 部门列表
const departments = ref([])
const loadDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    console.log('部门接口返回:', res)
    if (res.code !== 200) {
      ElMessage.error(res.msg || res.value || '获取部门列表失败')
      departments.value = []
      return
    }
    if (!Array.isArray(res.value)) {
      ElMessage.error(res.value || '获取部门列表失败')
      departments.value = []
      return
    }
    departments.value = res.value
    console.log('部门列表:', departments.value)
  } catch (e) {
    console.error('获取部门列表异常:', e)
    ElMessage.error('获取部门列表失败')
    departments.value = []
  }
}

// 表单验证规则
const userRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  defaultRole: [
    { required: true, message: '请选择默认角色', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return userForm.id ? '编辑用户' : '添加用户'
})

const userStore = useUserStore()
const currentRole = computed(() => {
  const info = userStore.userInfo || {}
  if (Array.isArray(info.roles) && info.roles.length > 0) return info.roles[0]
  return info.role || 'User'
})
const canUserAdd = () => currentRole.value === 'Boss' || currentRole.value === 'Manager'

const canEditOrDelete = () => {
  if (currentRole.value === 'Boss') return true
  if (currentRole.value === 'Manager') return true
  return false
}

// 方法
const handleSearch = () => {
  pagination.current = 1
  loadUserList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    status: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadUserList()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleAddUser = () => {
  if (!canUserAdd()) {
    ElMessage.error('权限不足')
    return
  }
  resetUserForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  if (!canEditOrDelete()) {
    ElMessage.error('权限不足')
    return
  }
  Object.assign(userForm, {
    id: row.id || row.ID,
    account: row.account || row.Account,
    departmentID: (row.departmentID || row.departmentId || row.DepartmentID || '').toString(),
    defaultRole: row.defaultRole || row.DefaultRole || 'User',
    isActived: row.isActived ?? row.IsActived ?? true,
    isDeleted: row.isDeleted || row.IsDeleted,
    remarks: row.remarks || row.Remarks || ''
  })
  dialogVisible.value = true
}

// 移除状态切换功能，因为后端没有这个功能

const handleDelete = async (row) => {
  if (!canEditOrDelete()) {
    ElMessage.error('权限不足')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.account || row.Account}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用API删除用户
    await userAPI.deleteUser(row.id || row.ID)
    ElMessage.success('删除成功')
    await loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

const handleSubmit = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()
    submitLoading.value = true

    // 处理部门字段：如果为null或空字符串则设为null
    const submitData = { ...userForm, departmentId: userForm.departmentID || null }

    // 调用API保存用户
    if (userForm.id) {
      // 更新用户
      await userAPI.updateUser(userForm.id, submitData)
      ElMessage.success('更新成功')
      // 如果当前登录用户修改了自己的角色，刷新用户信息
      if (userForm.id === userStore.userInfo.id) {
        await userStore.refreshUserInfo()
      }
    } else {
      await userAPI.addUser(submitData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    await loadUserList() // 保存后强制刷新用户列表
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetUserForm()
}

const resetUserForm = () => {
  Object.assign(userForm, {
    id: '',
    account: '',
    password: '',
    departmentID: '',
    defaultRole: 'User',
    isActived: true,
    isDeleted: false,
    remarks: ''
  })
  userFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadUserList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadUserList()
}

const loadUserList = async () => {
  loading.value = true
  try {
    const res = await userAPI.getUsers({
      account: searchForm.username,
      isActived: searchForm.status === 'active' ? true : searchForm.status === 'inactive' ? false : undefined,
      page: pagination.current,
      size: pagination.size
    })
    if (res.code === 200 && Array.isArray(res.value)) {
      userList.value = res.value.map(user => ({
        ...user,
        departmentID: String(user.departmentID || user.departmentId || user.DepartmentID || ''),
        avatar: user.avatar || user.Avatar || ''
      }))
      pagination.total = res.total || res.value.length
    } else {
      userList.value = []
      pagination.total = 0
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (e) {
    userList.value = []
    pagination.total = 0
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门名称
const getDepartmentName = (id) => {
  if (!id) return ''
  const dept = departments.value.find(d => String(d.id || d.ID) === String(id))
  if (!dept) return ''
  return dept.departName || dept.DepartName || dept.departmentName || ''
}

// 生命周期
onMounted(() => {
  loadDepartments()
  loadUserList()
})
</script>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
  }

  .table-card {
    border-radius: 8px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #303133;

      .table-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

/* 移除 el-avatar 边框样式 */
.el-avatar {
  border: none !important;
  box-shadow: none !important;
}
</style>
